/* Filename: primer0.c
 * No.86.线程-线程竞争实例1
 * Description:
 * 多线程去计算某一范围内的质数
 * $ gcc -Wall primer0.c -o primer0 -lpthread
 * Last modified: humble 2020-09-01 21:04:58
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#define LEFT (30000000)
#define RIGHT (30000200)
#define THRNUM (RIGHT - LEFT +1)


static void *thr_primer(void *p);

int main(int argc, char **argv)
{
    int i,err;
    pthread_t tid[THRNUM];

    for(i = LEFT; i <= RIGHT; i++){
        err = pthread_create(tid + (i - LEFT), NULL, thr_primer, (void *)i); //如果把i的地址则会有竞争
        if(err){
            //发生错误就收尸已经创建成功的线程
            //while(--i < 0){ pthread_join(tid[i - LEFT], NULL); } //未测
            fprintf(stderr, "pthread_create():%s\n", strerror(err));
            exit(1);
        }
    }

    for(i = LEFT; i <= RIGHT; i++){ //收尸
        pthread_join(tid[i - LEFT], NULL);
    }

    exit(0);
}

static void *thr_primer(void *p)
{
    int i, j, mark;
    i = (int)p;
    mark = 1;
    for(j = 2; j < i/2; j++) {
        if(i % j == 0){
            mark = 0;
            break;
        }
    }

    if(mark == 1){
        printf("%d is a primer\n", i);
    }

    pthread_exit(NULL);
}
